<template>
  <div class="app-container">
    <h1>我喜欢</h1>
    <div v-if="loading">加载中...</div>
    <div v-else>
      <p><strong>用户ID：</strong>{{ userStore.id }}</p>
      <p><strong>用户名：</strong>{{ userStore.name }}</p>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['UserTopSongs:UserTopSongs:export']"
        >导出</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="currentPageData" style="width: 100%">
      <!-- 添加行号列 -->
      <el-table-column width="150" align="center">
        <template #default="scope">
          <span style="margin-left: 16px">{{ scope.$index + 1 + (currentPage - 1) * pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="歌曲名称" prop="trackTitle" />
      <el-table-column label="歌手" prop="artistName" />
      <el-table-column label="播放次数" prop="trackPlayCount" />
    </el-table>
    <el-pagination
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="loveList.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加或修改用户Top10歌曲对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="UserTopSongsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="歌曲ID" prop="trackId">
          <el-input v-model="form.trackId" placeholder="请输入歌曲ID" />
        </el-form-item>
        <el-form-item label="播放占比" prop="totalPlayratio">
          <el-input v-model="form.totalPlayratio" placeholder="请输入播放占比" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserTopSongs">
import { listUserTopSongs, getUserTopSongs, delUserTopSongs, addUserTopSongs, updateUserTopSongs } from "@/api/UserTopSongs/UserTopSongs";
import useUserStore from '@/store/modules/user'
import {getLoveTitles} from "@/api/tracks/tracks.js";
import {computed, onMounted, ref} from "vue";

const userStore = useUserStore()


const { proxy } = getCurrentInstance();

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return loveList.value.slice(start, end);
});
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const loveList = ref([]);
const currentPage = ref(1); // 当前页码
const pageSize = ref(10);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    trackId: null,
    totalPlayratio: null
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  const currentUserId = userStore.id;
  getLoveList(currentUserId);
});

function handleSizeChange(newSize) {
  pageSize.value = newSize;
}

/** 处理页码变化 */
function handleCurrentChange(newPage) {
  currentPage.value = newPage;
}
function getLoveList(currentUserId) {
  loading.value = true;
  getLoveTitles(currentUserId).then(response => {
    console.log("API 返回的数据：", response.data);
    // 处理返回的数据，替换 + 和 /_/
    loveList.value = response.data.map(item => ({
      trackTitle: decodeURIComponent(item.trackTitle.replace(/\+/g, ' ').replace("/_/","——")),
      artistName: decodeURIComponent(item.artistName.replace(/\+/g, ' ').replace("/_/","——")),
      trackPlayCount: item.trackPlayCount
    }));
    console.info(loveList.value);
    loading.value = false;
  }).catch(error => {
    console.error("获取收藏歌曲详情失败：", error);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    trackId: null,
    totalPlayratio: null
  };
  proxy.resetForm("UserTopSongsRef");
}



/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户Top10歌曲";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _userId = row.userId || ids.value
  getUserTopSongs(_userId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户Top10歌曲";
  });
}

</script>
